local Lang = require("common.Lang")
local Util = require("common.Util")
local CommonDB = require("common.CommonDB")
local InnerMsg = require("core.InnerMsg")
local MiddleManager = require("middle.MiddleManager")
local MiddleLogic = require("middle.MiddleLogic")
local MiddleConnect = require("middle.MiddleConnect")

LAST_HEARTBEAT_TIME = LAST_HEARTBEAT_TIME or nil -- 上次收到心跳包的時間
LAST_SEND_HB_TS = LAST_SEND_HB_TS or nil -- 上次發送心跳包的時間

--定时发心跳30秒1次
function heartbeat()
    if _G.is_middle == true then return end

    if MiddleConnect.IS_MIDDLE_CONNECT ~= true then return end

    local now = os.time()
    if LAST_SEND_HB_TS == nil or now - LAST_SEND_HB_TS >= 30 then
        LAST_SEND_HB_TS = now
    
        -- logic连middle 所以logic向middle发心跳
        local msg = InnerMsg.lw.LW_HEARTBEAT
        
        msg.svrIndexData = msg.svrIndexData or {}
        Util.cleanTable(msg.svrIndexData)
        
        local mergeSvrIndexTb = CommonDB.getMergeSvrIndex()
        if mergeSvrIndexTb and mergeSvrIndexTb[1] then
            for i = 1, #mergeSvrIndexTb do
                msg.svrIndexData[i] = mergeSvrIndexTb[i]
            end
        end

        InnerMsg.sendMsg(0, msg)   
    end
end


function LW_HEARTBEAT(fd, msg)
    print("LW_HEARTBEAT", msg.svrIndexData)

    MiddleManager.onHeartbeat(fd, msg.svrIndexData)

    msg = InnerMsg.wl.WL_HEARTBEAT
    InnerMsg.sendMsg(fd, msg)  
end

function WL_HEARTBEAT(fd, msg)
    LAST_HEARTBEAT_TIME = os.time()
end

-- 设置开服时间
function LW_OS(fd, msg)
	local value = msg.value
	if value == nil then
		local openSvrTime = CommonDB.getServerOpenTime()
		if openSvrTime == 0 then
			MiddleLogic.sendWLBroadcast(fd, msg.uuid, Lang.DRILL_NOT_SET_OPEN_TIME)
		else
			local tb = os.date("%Y%m%d", openSvrTime)
			MiddleLogic.sendWLBroadcast(fd, msg.uuid, Lang.DRILL_CUR_TIME..tb)
		end
	else
		local now = os.time()
		local temp = Util.getDayStartTime(now)
		temp = temp - (value - 1) * 24 * 3600
	
		CommonDB.setServerOpenTime(temp)
		
		local tb = os.date("%Y%m%d", temp)
        MiddleLogic.sendWLBroadcast(fd, msg.uuid, Lang.DRILL_CUR_TIME..tb)
	end	
end

